import Taro, {Component} from '@tarojs/taro'
import {View, Text, Image, Textarea, Swiper, SwiperItem} from '@tarojs/components'
import {AtModal, AtModalHeader, AtModalContent, AtModalAction} from "taro-ui"
import './question.less'
import {
    arrow_down,
    arrow_up,
    ce1_backgroud, checkmark,
    coupon_icon, poker_bg,
    question_bg,
    question_button, resize, rotateFun, start,AugurSelect_btn
} from "../../constants/oss_consts";
import {formatNumber, interceptArray, showToast} from "../../util/app_tool";
import {
    getDailyTitles,
    getPayCalcs, getPrepay,
    getPreQuestions,
    getQuestionPrePay,
    postQuestions, putQuestions
} from "../../action/request_action";
import {IsPublish, MLoginInfo} from "../../constants/enum_consts";

let timer = null;

export default class Question extends Component {

    config = {
        navigationBarTitleText: '提问'
    }

    constructor(props) {
        super(props);
        this.state = {
            questionProduct: 0.00,
            textAreaValue: '',
            questionsId: 0,
            barrageList_arr: [],
            barrageList_obj: [],
            barrageList: [],
            phoneWidth: 0,
            couponOpen: false,
            isPublish: false,
            selectedIndex: -1,
            selectedItemIndex: -1,
            isOpenedModal: false,
            questionsObj: {},
            selectPoker: {}
        }
    }

    componentWillMount() {
        const that = this;
        Taro.getSystemInfo({
            success: function (res) {
                console.log('ww', res)
                that.setState({
                    phoneWidth: res.windowWidth - 100
                })
            }
        });
    }

    componentDidMount() {
        let that = this;
        let paramStr = this.$router.params.paramStr;
        let mLoginInfo = Taro.getStorageSync(MLoginInfo);
        let selectPoker = JSON.parse(decodeURIComponent(paramStr));
        this.setState({
            isPublish: Taro.getStorageSync(IsPublish),
            selectPoker: selectPoker,
            textAreaValue: selectPoker.questions,
            mLoginInfo: mLoginInfo
        });
        // that.getData();
    }

    componentWillUnmount() {
        clearInterval(this.timer);
    }

    componentDidHide() {
        clearInterval(timer);
    }


    componentDidShow() {
    }

    getData() {
        const that = this;
        // 添加弹幕所需的时间，初始位置
        getPreQuestions({}, function (data) {
            let hotTopics = [];
            for (let i = 0; i < 4; i++) {
            }
            hotTopics = hotTopics.concat(data.hotTopics);

            let questionProduct = data.questionProduct;
            let coupons = data.coupons ? data.coupons : [];
            let list = [];
            for (let i = 0; i < hotTopics.length; i++) {
                list.push({
                    width: that.state.phoneWidth,
                    time: 17,
                    height: 20,
                    content: hotTopics[i].question,
                    id: hotTopics[i].id,
                    score: hotTopics[i].score,
                    createTime: hotTopics[i].createTime,
                    modifyTime: hotTopics[i].modifyTime,
                    isDel: hotTopics[i].isDel,
                })
            }
            that.state.barrageList_arr = list;
            that.state.questionProduct = questionProduct;

            let couponsList = interceptArray(coupons, 2)
            that.state.couponsList = couponsList;
            that.state.coupons = coupons;

            that.setState({
                barrageList: interceptArray(list, Math.ceil(list.length / 4)),
                salesPrice: questionProduct.salesPrice
            })

            if (couponsList && couponsList.length > 0 && couponsList[0].length > 0) {
                that.couponButton(0, 0);
            }
            // setTimeout(() => {
            //     that.barrageListObj();
            // }, 200)
        });
    }

    /**
     *因为从后台获取到的是全部的数据，所以要把数据分开，让每条数据有先后之分
     *每隔一秒往barrageList 数组插入一条数据
     * */
    barrageListObj() {
        const that = this
        let {barrageList_arr, barrageList} = that.state;
        let i = 0;
        timer = setInterval(function () {
            if (barrageList.length > 1000) {
                barrageList = [];
            }
            barrageList.push(barrageList_arr[i]);
            console.log(barrageList.length);
            that.setState({
                barrageList: barrageList
            });

            if (i == barrageList_arr.length - 1) {
                i = 0;
            } else {
                i++;
            }
        }, 1000)
    }


    couponButton(indexItem, indexLi, e) {
        if (e) {
            e.stopPropagation();
        }
        let that = this;
        if (indexItem == -1 || indexLi == -1) {
            return
        }

        let selectedIndex = this.state.selectedIndex;
        let selectedItemIndex = this.state.selectedIndex;
        let salesPrice = this.state.questionProduct.salesPrice;

        if (selectedIndex == indexLi && selectedItemIndex == indexItem) {
            //二次点击,取消勾选优惠券
            this.setState({
                selectedIndex: -1,
                selectedItemIndex: -1,
                CouponId: 0,
                salesPrice: salesPrice
            })
        } else {
            let CouponId = this.state.couponsList[indexItem][indexLi].id;
            getPayCalcs({SalesPrice: salesPrice, CouponId: CouponId}, '', function (res) {

                that.setState({
                    salesPrice: res,
                    selectedIndex: indexLi,
                    selectedItemIndex: indexItem,
                    CouponId: CouponId
                })
            }, function (err) {

            });
        }
    }

    receiveCouponsBtn() {
        Taro.navigateTo({
            url: '/pages/find/activitys/activitys'
        })
    }

    initCouponView() {
        const {couponOpen, couponsList, selectedIndex, selectedItemIndex} = this.state
        return (
            <View className='coupon-parent-view' style={`height:${couponOpen ? 115 : 30}px`}>
                {
                    couponsList && couponsList.length > 0 ?
                        <Image onClick={this.couponClose2Open.bind(this)} className='down-img'
                               src={couponOpen ? arrow_down : arrow_up}></Image>
                        :
                        ''
                }
                {
                    couponOpen ?
                        <Swiper
                            className='test-h'
                            indicatorColor='#999'
                            indicatorActiveColor='#333'
                            displayMultipleItems={1}
                            vertical={false}
                            circular={false}
                            indicatorDots={false}
                            interval={2000}
                            autoplay={false}>
                            {
                                couponsList.map((item, indexItem) => (
                                    <SwiperItem key={indexItem}>
                                        {
                                            item.map((li, indexLi) => (
                                                <View key={indexLi}
                                                      onClick={this.couponButton.bind(this, indexItem, indexLi)}
                                                      className='coupon-view'>
                                                    {
                                                        selectedItemIndex == indexItem && selectedIndex == indexLi ?
                                                            <Image className='checkmark-img' src={checkmark}></Image>
                                                            : ''
                                                    }

                                                    <Image className='coupon-view-img' src={coupon_icon}></Image>

                                                    <View className='coupon-text'>
                                                        <View className='font-size-14'>{li.title}</View>
                                                        <View className='font-size-12'>{li.amountStr}</View>
                                                        <View
                                                            className='font-size-12 '>时限: {li.usableStartTime.substring(5, 10).replace('-', '.')}--{li.usableEndTime.substring(5, 10).replace('-', '.')}</View>
                                                    </View>
                                                </View>
                                            ))
                                        }
                                    </SwiperItem>
                                ))
                            }
                        </Swiper>
                        :
                        couponsList && couponsList.length > 0 && couponsList[0].length > 0 ?
                            <View className='coupon-text-view'>
                                <Text>优惠券:</Text>
                                <Text>￥ {couponsList[0][0].amountStr}</Text>
                                <Text>{couponsList[0][0].title}</Text>
                            </View>
                            :
                            <View className='coupon-text-view'>
                                <Text></Text>
                                <Text onClick={this.receiveCouponsBtn.bind(this)}>你还没有优惠券，免费去领取</Text>
                                <Text></Text>
                            </View>
                }


            </View>
        )
    }

    inputListener(e) {
        let value = e.detail.value;
        this.setState({
            textAreaValue: value
        })
    }

    clickBarrage(item) {
        this.setState({
            textAreaValue: item.content,
            questionsId: item.id
        })
    }

    everyDayTest() {
        Taro.navigateTo({
            url: '../select_poker/select_poker?sourceName=find'
        })
    }


    questionCommit() {
        let that = this;

        getPrepay({orderId: that.state.questionsObj.orderId}, function (data) {
            let map = {
                timeStamp: data.timeStamp,
                package: data.package,
                paySign: data.paySign,
                signType: data.signType,
                nonceStr: data.nonceStr,
            }
            Taro.requestPayment({
                ...map,
                success: function (res) {
                    Taro.redirectTo({
                        url: '/pages/answer/detail/detail?id=' + data.orderId + '&type=pay'
                    })
                },
                fail: function (res) {
                    showToast('请重新支付或联系管理员');
                }
            })
        });
    }

    couponClose2Open(type, e) {
        if (type == 'input' && !this.state.couponOpen) {
            this.setState({
                couponOpen: false,
            })
        } else {
            this.setState({
                couponOpen: !this.state.couponOpen,
            })
        }
    }

    amountProcessing(num) {
        let amout = formatNumber(num || 0.00);
        return amout.split('.');
    }


    startBtn() {
        let that = this;
        if (this.state.textAreaValue && this.state.textAreaValue.length > 0) {
            let selectPoker = that.state.selectPoker;
            selectPoker.questions = that.state.textAreaValue;
            putQuestions(selectPoker, '', function (res) {
                that.state.questionsObj = res
                that.setState({
                    isOpenedModal: true
                })
            });

        } else {
            showToast('请输入您要占卜的问题!')
        }
    }
    selectMasterBtn() {
        let that = this;
        if (this.state.textAreaValue && this.state.textAreaValue.length > 0) {
            let selectPoker = that.state.selectPoker;
            selectPoker.questions = that.state.textAreaValue;
            debugger
            let paramStr = encodeURIComponent(JSON.stringify(selectPoker));
            Taro.redirectTo({
                url: '../select_poker/select_master?paramStr='+paramStr
            })

        } else {
            showToast('请输入您要占卜的问题!')
        }
    }
    goToCollect() {

        Taro.navigateTo({
            url: '../find/activitys/activitys'
        })
        this.setState({
            isOpenedModal: false
        })
    }

    closeModal() {
        this.setState({
            isOpenedModal: false
        })
    }

    render() {
        const {textAreaValue, isOpenedModal, selectPoker, questionsObj, mLoginInfo, barrageList, isPublish, couponOpen} = this.state;
        let coupon = questionsObj.coupon || {};
        let questionProductData = questionsObj.questionProduct || {};
        let normalPrice = questionProductData.normalPrice;
        let salesPrice = questionProductData.salesPrice;
        let isShowCouponButton = questionsObj.isShowCouponButton;

        let firstCard = selectPoker.firstCard || {};
        let secondCard = selectPoker.secondCard || {};
        let thirdCard = selectPoker.thirdCard || {};

        return (
            <View className='question-view'>

                {
                    isOpenedModal ?
                        <AtModal isOpened onClose={this.closeModal.bind(this)}>
                            <AtModalHeader>支付等待占卜师解答</AtModalHeader>
                            <AtModalContent>
                                <View className='pd-10'>需支付:<Text
                                    className=' ml-10 font-size-20'>￥{questionsObj.payable / 100}</Text>元</View>
                                <View className='pd-10 color-text-5'>原价:<Text
                                    className='ml-10 font-size-14'>￥{salesPrice / 100}</Text>元</View>
                                {
                                    !coupon || coupon == null || coupon == {} ?
                                        isShowCouponButton ?
                                            <View className='display-flex'>
                                                <View className='text-align-center flex1'
                                                      style='line-height:30px'>
                                                    {questionsObj.couponStr}
                                                </View>
                                                <View onClick={this.goToCollect.bind(this)}
                                                      className='goto-view'>去领取</View>
                                            </View>
                                            :
                                            ''
                                        :
                                        <View className='pd-10'>优惠券:<Text
                                            className='ml-10 font-size-14 '>￥{coupon.amountStr}</Text></View>

                                }

                                <View className='tip-view'>{mLoginInfo.questionPayInfo || ''}</View>
                            </AtModalContent>
                            <AtModalAction> <Button onClick={this.questionCommit.bind(this)}>支付</Button> <Button
                                onClick={this.closeModal.bind(this)}>狠心离开</Button> </AtModalAction>
                        </AtModal>
                        :
                        ''
                }


                <View className='display-flex justify-contentr-sb plr-10' style='padding-top:10px'>
                    {
                        firstCard.picUrl?
                            <View>
                                <Image className='result_poker-img'
                                       src={firstCard.picUrl.concat(resize).concat(rotateFun(firstCard.isInversion))}></Image>
                                <View
                                    className='align-items-center text-align-center font-size-14 fff mt-5'>{firstCard.cardName}</View>
                            </View>
                            :
                            ''
                    }

                    {
                        secondCard.picUrl?
                            <View>
                                <Image className='result_poker-img'
                                       src={secondCard.picUrl .concat(resize).concat(rotateFun(secondCard.isInversion))}></Image>
                                <View
                                    className='align-items-center text-align-center font-size-14 fff mt-5'>{secondCard.cardName}</View>
                            </View>
                            :
                            ''

                    }

                    {
                        thirdCard.picUrl?
                            <View>
                                <Image className='result_poker-img'
                                       src={thirdCard.picUrl.concat(resize).concat(rotateFun(thirdCard.isInversion))}></Image>
                                <View
                                    className='align-items-center text-align-center font-size-14 fff mt-5'>{thirdCard.cardName}</View>
                            </View>
                            :
                            ''
                    }

                </View>

                {
                    !isOpenedModal ?
                        <View className='input-parent-view mt-20'>
                            <View className='fff' style='text-align:left;padding-left:25px'>请输入问题</View>
                            <View className='p-relative'>
                                <Textarea onClick={this.couponClose2Open.bind(this, 'input')} show-confirm-bar={false}
                                          cursor-spacing="110" onInput={this.inputListener.bind(this)}
                                          maxlength={150} className='input-view'
                                          value={textAreaValue} placeholder='请输入'></Textarea>
                                <View className="current-word-num">还可以输入{150 - textAreaValue.length}个字</View>
                            </View>
                        </View>
                        :
                        ''
                }
                
                <View className='start-view'>
                    <Image onClick={this.startBtn.bind(this)} className='start-image'
                           src={start} mode='widthFix'></Image>
                </View>
                <View className='start-view'>
                    <Text onClick={this.selectMasterBtn.bind(this)} style={`background-image: url(${AugurSelect_btn});-moz-background-size:100% 100%; background-size:100% 100%;font-size: 14px;padding: 16px;color: #fff;`}>选择占卜师</Text>
                    {/* <Image onClick={this.selectMasterBtn.bind(this)} className='start-image'
                           src={AugurSelect_btn} mode='widthFix'></Image> */}
                </View>
            </View>

        )
    }
}
